const {db} = require('../../config/dbconfig')

exports.addArticlelikes = async (req, res, next) => {
    const {article_id, user_id} = req.body;

    if (!article_id || !user_id) {
        return res.status(400).json({error: 'Article ID and User ID are required'});
    }

    // 开启事务
    db.getConnection((err, connection) => {
        if (err) {
            console.error('Error establishing database connection:', err);
            return res.status(500).json({error: 'Error establishing database connection'});
        }

        connection.beginTransaction(err => {
            if (err) {
                connection.release();
                console.error('Error beginning transaction:', err);
                return res.status(500).json({error: 'Error beginning transaction'});
            }

            const sql1 = 'INSERT INTO ArticleLikes (article_id, user_id) VALUES (?, ?)';
            connection.query(sql1, [article_id, user_id], (error, results) => {
                if (error) {
                    connection.rollback(() => {
                        connection.release();
                        console.error('Error adding article like:', error);
                        return res.status(500).json({error: 'Error adding article like'});
                    });
                }

                const sql2 = 'UPDATE Articles SET likes = likes + 1 WHERE id = ?';
                connection.query(sql2, [article_id], (error, results) => {
                    if (error) {
                        connection.rollback(() => {
                            connection.release();
                            console.error('Error updating article likes:', error);
                            return res.status(500).json({error: 'Error updating article likes'});
                        });
                    }

                    connection.commit(err => {
                        if (err) {
                            connection.rollback(() => {
                                connection.release();
                                console.error('Error committing transaction:', err);
                                return res.status(500).json({error: 'Error committing transaction'});
                            });
                        }

                        connection.release();
                        res.status(201).json({message: 'Article like added successfully'});
                    });
                });
            });
        });
    });
}

exports.deleteArticlelikes = async (req, res, next) => {
    const articleId = req.params.articleId;
    const userId = req.params.userId;

    // 开启事务
    db.getConnection((err, connection) => {
        if (err) {
            console.error('Error establishing database connection:', err);
            return res.status(500).json({error: 'Error establishing database connection'});
        }

        connection.beginTransaction(err => {
            if (err) {
                connection.release();
                console.error('Error beginning transaction:', err);
                return res.status(500).json({error: 'Error beginning transaction'});
            }

            const sql1 = 'DELETE FROM ArticleLikes WHERE article_id = ? AND user_id = ?';
            connection.query(sql1, [articleId, userId], (error, results) => {
                if (error) {
                    connection.rollback(() => {
                        connection.release();
                        console.error('Error deleting article like:', error);
                        return res.status(500).json({error: 'Error deleting article like'});
                    });
                }

                const sql2 = 'UPDATE Articles SET likes = likes - 1 WHERE id = ?';
                connection.query(sql2, [articleId], (error, results) => {
                    if (error) {
                        connection.rollback(() => {
                            connection.release();
                            console.error('Error updating article likes:', error);
                            return res.status(500).json({error: 'Error updating article likes'});
                        });
                    }

                    connection.commit(err => {
                        if (err) {
                            connection.rollback(() => {
                                connection.release();
                                console.error('Error committing transaction:', err);
                                return res.status(500).json({error: 'Error committing transaction'});
                            });
                        }
                        connection.release();
                        res.json({message: 'Article like deleted successfully'});
                    });
                });
            });
        });
    });
}

exports.getArticlelikes = async (req, res, next) => {
    const articleId = req.params.articleId;
    const sql = `
    SELECT Articles.id AS article_id, Articles.title, Articles.content, 
           Users.id AS user_id, Users.username
    FROM Articles
    INNER JOIN ArticleLikes ON Articles.id = ArticleLikes.article_id
    INNER JOIN Users ON ArticleLikes.user_id = Users.id
    WHERE Articles.id = ?
  `;
    db.query(sql, [articleId], (error, results) => {
        if (error) {
            console.error('Error fetching article likes:', error);
            return res.status(500).json({error: 'Error fetching article likes'});
        }
        // 将结果封装为一个对象
        const likesForArticle = {
            article_id: articleId,
            likes: []
        };
        results.forEach(row => {
            likesForArticle.likes.push({
                user_id: row.user_id,
                username: row.username
            });
        });
        res.json(likesForArticle);
    });
}
exports.getAllArticlelikes = async (req, res, next) => {
    const sql = `
    SELECT Articles.id AS article_id, Articles.title, Articles.content, 
           Users.id AS user_id, Users.username
    FROM Articles
    INNER JOIN ArticleLikes ON Articles.id = ArticleLikes.article_id
    INNER JOIN Users ON ArticleLikes.user_id = Users.id
  `;
    db.query(sql, (error, results) => {
        if (error) {
            console.error('Error fetching article likes:', error);
            return res.status(500).json({error: 'Error fetching article likes'});
        }
        // 将结果封装为一个对象
        const likesByArticle = {};
        results.forEach(row => {
            if (!likesByArticle[row.article_id]) {
                likesByArticle[row.article_id] = {
                    article_id: row.article_id,
                    title: row.title,
                    content: row.content,
                    likes: []
                };
            }
            likesByArticle[row.article_id].likes.push({
                user_id: row.user_id,
                username: row.username
            });
        });
        res.json(likesByArticle);
    });
}